package model.data.database;

import java.util.ArrayList;
import java.util.List;

import model.OrderLine;
import model.data.OrderLineStore;

public class OrderLineTable implements OrderLineStore {
	/* Handles requests to the database */
	DatabaseHandler dbHandler;
	
	/** Constructs a new category table */
	public OrderLineTable() {
		this.dbHandler = new DatabaseHandler();
	}
	@Override
	public void write(OrderLine orderLine) throws Exception{
		this.dbHandler.callUpdateProcedure("sp_insertorderline(?,?,?,?)", orderLine.getId(), orderLine.getQuantity(), orderLine.getPrice(), orderLine.getProduct());
	}

	@Override
	public void update(OrderLine orderLine) {
		// TODO Auto-generated method stub
	}

	@Override
	public void delete(OrderLine orderLine) throws Exception {
		this.dbHandler.callUpdateProcedure("sp_deleteorderline(?)", orderLine.getId());
	}

	@Override
	public int getCount() throws Exception {
		int count = 0;
		ArrayList<DataRecord> records;

		// Get records
		records = (ArrayList<DataRecord>)this.dbHandler.callQueryProcedure("sp_getcountorderline");
		
		// Fill list
		for (DataRecord dr : records) {
			count = Integer.parseInt(dr.getValue("Result"));
		}
		
		// Return result
		return count;
	}

	@Override
	public List<OrderLine> getById(long id) throws Exception {
		ArrayList<OrderLine> orderLines;
		ArrayList<DataRecord> records;
		
		// Get records
		records = (ArrayList<DataRecord>)this.dbHandler.callQueryProcedure("sp_getbyidorderline(?)", id);
		
		// Create list
		orderLines = new ArrayList<OrderLine>();
		
		// Fill list
		// TODO add order and price
		for (DataRecord dr : records) {
			OrderLine orderLine = new OrderLine();
			orderLine.setId(Long.parseLong(dr.getValue("CategoryID")));
			orderLine.setOrderId(Long.parseLong(dr.getValue("OrderID")));
			orderLine.setProductId(Long.parseLong(dr.getValue("ProductID")));
			orderLine.setQuantity(Integer.parseInt(dr.getValue("Quantity")));
			orderLine.setPrice(Long.parseLong(dr.getValue("Price")));
			orderLines.add(orderLine);
		}
		
		// Return result
		return orderLines;
	}
}
